//
//  PetDetailViewController.swift
//  PetManager
//
//  Created by 吴翰林 on 2019/11/5.
//  Copyright © 2019 吴翰林. All rights reserved.
//

import UIKit
import MessageUI

protocol PetDetailViewControllerDelegate: class {
    func PetDetailViewController(_ controller: PetDetailViewController, didFinishAdding category: Pet)
    func PetDetailViewController(_ controller: PetDetailViewController, didFinishEditing category: Pet)
    func PetDetailViewController(_ controller:PetDetailViewController,didFinishDelete category:Pet)
}

class PetDetailViewController: UITableViewController, UITextFieldDelegate, IconPickerViewControllerDelegate,MFMailComposeViewControllerDelegate {
    weak var delegate: PetDetailViewControllerDelegate?

    var petToEdit: Pet?
    
    @IBOutlet weak var categoryText: UITextField!
    @IBOutlet weak var doneBarButton: UIBarButtonItem!
    @IBOutlet weak var iconImageView: UIImageView!
    
    //管理 manager
    @IBOutlet weak var managerNum: UILabel!
    @IBAction func managerAdd(_ sender: UIButton) {
        var mNum = Int(managerNum.text!)!
        mNum = mNum + 1
        managerNum.text = "\(mNum)"
    }
    
    @IBAction func managerMinus(_ sender: UIButton) {
        var mNum = Int(managerNum.text!)!
        if mNum > 0 {
            mNum = mNum - 1
            managerNum.text = "\(mNum)"
        }
    }
    
    //订购 order
    @IBOutlet weak var orderNum: UILabel!
    @IBAction func orderAdd(_ sender: UIButton) {
        var oNum = Int(orderNum.text!)!
        oNum = oNum + 1
        orderNum.text = "\(oNum)"
    }
    @IBAction func orderMinus(_ sender: UIButton) {
        var oNum = Int(orderNum.text!)!
        if oNum > 0 {
            oNum = oNum - 1
            orderNum.text = "\(oNum)"
        }
    }
    @IBAction func theOrder(_ sender: UIButton) {
        if MFMailComposeViewController.canSendMail(){
            let mailComposeViewController = configureMailComposeViewController()
            self.present(mailComposeViewController,animated: true,completion: nil)
            
        }else{
            self.showSendMailErrorAlert()
        }
    }
    
    
    //删除 delete
    @IBOutlet weak var delete: UIBarButtonItem!
    @IBAction func deleteButton(_ sender: Any) {
        if let category = self.petToEdit {
            let a = UIAlertController(title: "删除？", message: "是否删除:\(category.name)", preferredStyle: .alert)
        a.addAction(UIAlertAction(title: "确定", style: .default){ _ in
                
                self.delegate?.PetDetailViewController(self, didFinishDelete: category)
            self.dismiss(animated: true, completion: nil)

        })
        a.addAction(UIAlertAction(title: "取消", style: .cancel){ _ in})
        self.present(a,animated: true,completion: nil)
        }
    }
    
    
    
    
    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        switch result.rawValue{
                case MFMailComposeResult.sent.rawValue:
                    print("邮件已发送")
                case MFMailComposeResult.cancelled.rawValue:
                    print("邮件已取消")
                case MFMailComposeResult.saved.rawValue:
                    print("邮件已保存")
                case MFMailComposeResult.failed.rawValue:
                    print("邮件发送失败")
                default:
                    print("邮件没有发送")
                    break
                }

                controller.dismiss(animated: true, completion: nil)
    }
    
    func configureMailComposeViewController() -> MFMailComposeViewController {
        let mailComposeVC = MFMailComposeViewController()
        mailComposeVC.mailComposeDelegate = self
        mailComposeVC.setToRecipients(["1161474617@qq.com"])
        mailComposeVC.setSubject("订购宠物")
        mailComposeVC.setMessageBody(orderNum.text!, isHTML: false)
        
        return mailComposeVC
    }
    
    func showSendMailErrorAlert() {

        let sendMailErrorAlert = UIAlertController(title: "无法发送邮件", message: "您的设备尚未设置邮箱，请在“邮件”应用中设置后再尝试发送。", preferredStyle: .alert)
        sendMailErrorAlert.addAction(UIAlertAction(title: "确定", style: .default) { _ in })
     self.present(sendMailErrorAlert, animated: true){}

    }
    
    
    var iconName = "Folder"
    
    override func viewDidLoad() {
        super.viewDidLoad()

        if let category = petToEdit {
            title = "详情"
            categoryText.text = category.name
            iconName = category.iconName
            managerNum.text = category.managerNum
            orderNum.text = category.orderNum
            doneBarButton.isEnabled = true
        }else{
           title = "新增宠物"
            delete.isEnabled = false
            
        }
        iconImageView.image = UIImage(named: iconName)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        categoryText.becomeFirstResponder()
    }
    
    override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
        if indexPath.section == 1 {
            return indexPath
        } else {
            return nil
        }
    }
    
    // MARK: - UITextFieldDelegate
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let oldText = textField.text! as NSString
        let newText = oldText.replacingCharacters(in: range, with: string)
        
        doneBarButton.isEnabled = newText.count > 0
        return true
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "PickIcon" {
            let controller = segue.destination as! IconPickerViewController
            controller.delegate = self
        }
    }
    
    @IBAction func done(_ sender: Any) {
        if let category = petToEdit {
            category.name = categoryText.text!
            category.iconName = iconName
            category.managerNum = managerNum.text!
            category.orderNum = orderNum.text!
            delegate?.PetDetailViewController(self, didFinishEditing: category)
        } else {
            let category = Pet(name: categoryText.text!,managerNum: managerNum.text!,orderNum: orderNum.text!)
            category.iconName = iconName
            delegate?.PetDetailViewController(self, didFinishAdding: category)
        }
    }
    
    @IBAction func cancel(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }
    
    func iconPicker(_ picker: IconPickerViewController, didPick iconName: String) {
        self.iconName = iconName
        iconImageView.image = UIImage(named: iconName)
        
        navigationController?.popViewController(animated: true)
    }
    
}
